package com.hncc.kumao.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;

import com.hncc.kumao.entity.BreakpointUploadTask;
import com.hncc.kumao.entity.NetdiskAccessToken;
import com.hncc.kumao.entity.OfflineDownloadTask;
import com.hncc.kumao.exception.KumaoNetdiskFileNotFoundException;
import com.hncc.kumao.util.ConstValue;
import com.hncc.kumao.util.MyDownloadProgress;
import com.hncc.kumao.util.MyFileUtils;
import com.hncc.kumao.util.OfflineDownloadUtils;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;

public class SMBOperation {
    
    private static String taskId;

    /**
     * 检查当前网盘信息是否有效
     * @param netdiskAccessToken 网盘信息
     * @return
     */
    public static boolean check(NetdiskAccessToken netdiskAccessToken, String filePath) {
        boolean exists = false;
        try {
            int index = filePath.indexOf("/", 2);
            String parengDir = "";
            if(index != -1) {
                parengDir = filePath.substring(0, index);
            } else {
                parengDir = filePath;
            }
            String checkUrl = "smb://" + netdiskAccessToken.getUsername() + ":" + 
                    netdiskAccessToken.getPassword() + "@" + netdiskAccessToken.getNetdiskUrl() + parengDir;
            SmbFile smbFile = new SmbFile(checkUrl);
            smbFile.setConnectTimeout(10000);
            exists = smbFile.exists();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return exists;
    }
    
    // 进行下载
    public static void download(OfflineDownloadTask offlineDownloadTask, NetdiskAccessToken netdiskAccessToken,
            final MyDownloadProgress progress) throws Exception {
        
        SmbFileInputStream sfis = null;
        FileOutputStream fos = null;
        try {
            taskId = offlineDownloadTask.getId();
            String baseUrl = "smb://" + netdiskAccessToken.getUsername() + ":" + 
                    netdiskAccessToken.getPassword() + "@" + netdiskAccessToken.getNetdiskUrl();
            String url = baseUrl + offlineDownloadTask.getFileUri();
            SmbFile smbFile = new SmbFile(url);
            boolean exists = smbFile.exists();
            if(!exists) {
                System.out.println("未找到该文件");
                throw new KumaoNetdiskFileNotFoundException("未找到该文件");
            }
            
            sfis = new SmbFileInputStream(smbFile);
            long contentLength = Long.parseLong(offlineDownloadTask.getFileSize());
            String fileSavePath = offlineDownloadTask.getFileSavePath();
            //创建文件输出流
            if (OfflineDownloadUtils.getTaskProgressState(taskId) == ConstValue.OD_TASK_STATE_GOING) {
                //先创建文件夹，防止文件夹不存在报错
                File tempFile = new File(fileSavePath);
                if (!tempFile.exists()) {
                    if (!tempFile.getParentFile().exists()) {
                        tempFile.getParentFile().mkdirs();
                    }
                }
                fos = new FileOutputStream(fileSavePath);
            }
            byte[] buffer = new byte[4096];
            int r = 0;
            long totalRead = 0;
            if (fos != null) {
                while (((r = sfis.read(buffer)) > 0)) {
                    if (OfflineDownloadUtils.getTaskProgressState(taskId) != ConstValue.OD_TASK_STATE_GOING) {
                        break;
                    }
                    fos.write(buffer, 0, r);
                    totalRead += r;
                    if (progress != null) {
                        //System.out.println(totalRead + "/" + contentLength);
                        progress.onProgress(totalRead, contentLength);
                    }
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            throw e;
        } finally {
            if (sfis != null) {
                sfis.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }
    
    //上传文件
    public static void upload(BreakpointUploadTask breakpointUploadTask, NetdiskAccessToken netdiskAccessToken) throws Exception {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            String baseUrl = "smb://" + netdiskAccessToken.getUsername() + ":" + 
                    netdiskAccessToken.getPassword() + "@" + netdiskAccessToken.getNetdiskUrl();
            String url = baseUrl + breakpointUploadTask.getFileUri();
            SmbFile smbFile = new SmbFile(url);
            smbFile.connect();
            
            File uploadFile = new File(breakpointUploadTask.getFileServerPath());
            inputStream = new FileInputStream(uploadFile);
            outputStream = new SmbFileOutputStream(smbFile);
            byte[] buffer = new byte[4096];
            int len = 0; // 读取长度
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            // 刷新缓冲的输出流
            outputStream.flush();
        } catch (Exception e) {
            //e.printStackTrace();
            throw e;
        } finally {
            if(inputStream != null) {
                inputStream.close();
            }
            if(outputStream != null) {
                outputStream.close();
            }
        }
    }
}
